import React, { useState } from 'react';
import { Radar, RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, ResponsiveContainer, Legend, Tooltip } from 'recharts';
import { useDiaryStore } from '../../store/diaryStore';
import { useChartContext } from '../../contexts/ChartContext';

interface MoodRadarChartProps {
  period?: 'week' | 'month' | 'quarter' | 'year';
}

interface RadarData {
  mood: string;
  current: number;
  previous: number;
  average: number;
}

const MoodRadarChart: React.FC<MoodRadarChartProps> = ({ period = 'month' }) => {
  const entries = useDiaryStore((state) => state.entries);
  const { filters, setFilters } = useChartContext();
  const [selectedPeriod, setSelectedPeriod] = useState(period);
  const [showComparison, setShowComparison] = useState(true);

  const moodColors = {
    happy: '#22c55e',
    sad: '#3b82f6',
    angry: '#ef4444',
    excited: '#f59e0b',
    calm: '#8b5cf6',
    anxious: '#f97316',
    content: '#06b6d4',
    frustrated: '#ec4899',
    grateful: '#84cc16',
    lonely: '#6b7280'
  };

  // Calculate date ranges
  const getPeriodDates = (period: string, offset: number = 0) => {
    const now = new Date();
    const start = new Date();
    const end = new Date();

    switch (period) {
      case 'week':
        start.setDate(now.getDate() - 7 * (offset + 1));
        end.setDate(now.getDate() - 7 * offset);
        break;
      case 'month':
        start.setMonth(now.getMonth() - (offset + 1));
        start.setDate(1);
        end.setMonth(now.getMonth() - offset);
        end.setDate(0);
        break;
      case 'quarter':
        const currentQuarter = Math.floor(now.getMonth() / 3);
        const targetQuarter = currentQuarter - offset;
        start.setMonth(targetQuarter * 3);
        start.setDate(1);
        end.setMonth((targetQuarter + 1) * 3);
        end.setDate(0);
        break;
      case 'year':
        start.setFullYear(now.getFullYear() - (offset + 1), 0, 1);
        end.setFullYear(now.getFullYear() - offset, 11, 31);
        break;
    }

    return { start: start.toISOString().split('T')[0], end: end.toISOString().split('T')[0] };
  };

  // Generate radar data
  const generateRadarData = (): RadarData[] => {
    const currentPeriod = getPeriodDates(selectedPeriod, 0);
    const previousPeriod = getPeriodDates(selectedPeriod, 1);
    
    // Get all unique moods
    const allMoods = Array.from(new Set(entries.map(entry => entry.mood).filter(Boolean)));
    
    // Count moods for current period
    const currentEntries = entries.filter(entry => {
      const entryDate = entry.date.split('T')[0];
      return entryDate >= currentPeriod.start && entryDate <= currentPeriod.end;
    });
    
    // Count moods for previous period
    const previousEntries = entries.filter(entry => {
      const entryDate = entry.date.split('T')[0];
      return entryDate >= previousPeriod.start && entryDate <= previousPeriod.end;
    });
    
    // Calculate overall average
    const allMoodCounts = allMoods.reduce((acc, mood) => {
      acc[mood] = entries.filter(entry => entry.mood === mood).length;
      return acc;
    }, {} as Record<string, number>);
    
    const totalEntries = entries.length;
    
    return allMoods.map(mood => {
      const currentCount = currentEntries.filter(entry => entry.mood === mood).length;
      const previousCount = previousEntries.filter(entry => entry.mood === mood).length;
      const totalCount = allMoodCounts[mood];
      
      // Calculate percentages
      const currentPercentage = currentEntries.length > 0 ? (currentCount / currentEntries.length) * 100 : 0;
      const previousPercentage = previousEntries.length > 0 ? (previousCount / previousEntries.length) * 100 : 0;
      const averagePercentage = totalEntries > 0 ? (totalCount / totalEntries) * 100 : 0;
      
      return {
        mood: mood.charAt(0).toUpperCase() + mood.slice(1),
        current: Math.round(currentPercentage * 10) / 10,
        previous: Math.round(previousPercentage * 10) / 10,
        average: Math.round(averagePercentage * 10) / 10
      };
    }).filter(data => data.current > 0 || data.previous > 0 || data.average > 0);
  };

  const radarData = generateRadarData();
  
  const handleMoodClick = (mood: string) => {
    const moodLower = mood.toLowerCase();
    setFilters({ moods: [moodLower] });
  };

  const clearFilters = () => {
    setFilters({ moods: [] });
  };

  const CustomTooltip = ({ active, payload, label }: any) => {
    if (active && payload && payload.length) {
      return (
        <div className="bg-white p-3 border border-warm-gray-200 rounded-lg shadow-lg">
          <p className="font-medium text-warm-gray-800 mb-2">{label}</p>
          {payload.map((entry: any, index: number) => (
            <p key={index} className="text-sm" style={{ color: entry.color }}>
              {entry.dataKey === 'current' ? `Current ${selectedPeriod}` : 
               entry.dataKey === 'previous' ? `Previous ${selectedPeriod}` : 'Overall average'}: {entry.value}%
            </p>
          ))}
          <p className="text-xs text-warm-gray-500 mt-2 cursor-pointer hover:text-blue-600"
             onClick={() => handleMoodClick(label)}>
            Click to filter by this mood
          </p>
        </div>
      );
    }
    return null;
  };

  const periodLabels = {
    week: 'Week',
    month: 'Month', 
    quarter: 'Quarter',
    year: 'Year'
  };

  return (
    <div className="bg-white rounded-lg shadow-sm border border-warm-gray-200 p-6">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-semibold text-warm-gray-800">
          Mood Patterns Radar
        </h3>
        <div className="flex items-center gap-2">
          <select
            value={selectedPeriod}
            onChange={(e) => setSelectedPeriod(e.target.value as any)}
            className="text-xs border border-warm-gray-300 rounded px-2 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            {Object.entries(periodLabels).map(([value, label]) => (
              <option key={value} value={value}>{label}</option>
            ))}
          </select>
          <button
            onClick={() => setShowComparison(!showComparison)}
            className={`text-xs px-2 py-1 rounded transition-colors ${
              showComparison 
                ? 'bg-blue-100 text-blue-700 hover:bg-blue-200' 
                : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
            }`}
          >
            Compare
          </button>
          {filters.moods && filters.moods.length > 0 && (
            <button
              onClick={clearFilters}
              className="text-xs bg-red-100 text-red-700 px-2 py-1 rounded hover:bg-red-200 transition-colors"
            >
              Clear Filter
            </button>
          )}
        </div>
      </div>

      {filters.moods && filters.moods.length > 0 && (
        <div className="mb-4 p-3 bg-blue-50 rounded-lg">
          <p className="text-sm text-blue-800">
            Filtered by mood: <span className="font-medium">{filters.moods.join(', ')}</span>
          </p>
        </div>
      )}

      {radarData.length === 0 ? (
        <div className="flex items-center justify-center h-64 text-warm-gray-500">
          <div className="text-center">
            <p className="text-lg mb-2">No mood data available</p>
            <p className="text-sm">Start writing entries with moods to see patterns</p>
          </div>
        </div>
      ) : (
        <div className="h-80">
          <ResponsiveContainer width="100%" height="100%">
            <RadarChart data={radarData} margin={{ top: 20, right: 30, bottom: 20, left: 30 }}>
              <PolarGrid gridType="polygon" className="stroke-warm-gray-200" />
              <PolarAngleAxis 
                dataKey="mood" 
                tick={{ fontSize: 12, fill: '#6b7280' }}
                className="text-warm-gray-600"
              />
              <PolarRadiusAxis 
                angle={90} 
                domain={[0, 'dataMax']}
                tick={{ fontSize: 10, fill: '#9ca3af' }}
                tickFormatter={(value) => `${value}%`}
              />
              
              <Radar
                name={`Current ${periodLabels[selectedPeriod as keyof typeof periodLabels]}`}
                dataKey="current"
                stroke="#3b82f6"
                fill="#3b82f6"
                fillOpacity={0.3}
                strokeWidth={2}
                dot={{ fill: '#3b82f6', strokeWidth: 2, r: 4 }}
              />
              
              {showComparison && (
                <>
                  <Radar
                    name={`Previous ${periodLabels[selectedPeriod as keyof typeof periodLabels]}`}
                    dataKey="previous"
                    stroke="#f59e0b"
                    fill="#f59e0b"
                    fillOpacity={0.2}
                    strokeWidth={2}
                    strokeDasharray="5 5"
                    dot={{ fill: '#f59e0b', strokeWidth: 2, r: 3 }}
                  />
                  
                  <Radar
                    name="Overall Average"
                    dataKey="average"
                    stroke="#6b7280"
                    fill="#6b7280"
                    fillOpacity={0.1}
                    strokeWidth={1}
                    strokeDasharray="3 3"
                    dot={{ fill: '#6b7280', strokeWidth: 1, r: 2 }}
                  />
                </>
              )}
              
              <Tooltip content={<CustomTooltip />} />
              <Legend 
                wrapperStyle={{ fontSize: '12px' }}
                iconType="line"
              />
            </RadarChart>
          </ResponsiveContainer>
        </div>
      )}

      <div className="mt-4 text-xs text-warm-gray-500">
        <p className="mb-1">
          <strong>Tip:</strong> Click on mood names in the tooltip to filter entries by that mood.
        </p>
        <p>
          Values represent the percentage of entries with each mood during the selected period.
        </p>
      </div>
    </div>
  );
};

export default MoodRadarChart;